import 'dart:async';

import 'package:fish_redux/fish_redux.dart';
import 'package:flutter/material.dart' hide Action;
import 'package:flutter_spinkit/flutter_spinkit.dart';

import 'action.dart';
import 'state.dart';

Widget buildView(
    HomeworkListState state, Dispatch dispatch, ViewService viewService) {
  List<DropdownMenuItem> classList() {
    final List<DropdownMenuItem> items = List();
    items.add(DropdownMenuItem(value: '', child: Text('全部班级')));
    state.classes?.forEach((klass) {
      items.add(
          DropdownMenuItem(value: klass['code'], child: Text(klass['name'])));
    });
    return items;
  }

  final ListAdapter adapter = viewService.buildAdapter();
  final ScrollController _scrollController = new ScrollController();
  _scrollController.addListener(() {
    // 如果下拉的当前位置到scroll的最下面
    if (_scrollController.position.pixels ==
        _scrollController.position.maxScrollExtent) {
      dispatch(HomeworkListActionCreator.onLoad());
    }
  });

  List<Widget> _listView() {
    var widgets = <Widget>[];
    if (adapter.itemCount == 0) {
      if (!state.isLoading) {
        widgets.add(Center(
            child: Column(
          children: <Widget>[
            Image.asset("assets/images/empty_list.png",
                width: 200, height: 200, fit: BoxFit.fill),
            Text('让AI助手为您提升批改效率！', style: TextStyle(color: Colors.grey))
          ],
        )));
      }
    } else {
      widgets.add(ListView.builder(
        key: new PageStorageKey('homework_list'),
        physics: AlwaysScrollableScrollPhysics(),
        // work when several items
        itemBuilder: (context, index) {
          if (index == adapter.itemCount) {
            return Padding(
              padding: const EdgeInsets.all(8.0),
              child: new Center(
                child: new Opacity(
                  opacity: state.isLoading ? 0.0 : 1.0,
                  child: Text(index != 0 ? '没有更多了' : '',
                      style: TextStyle(color: Colors.grey)),
                ),
              ),
            );
          } else {
            return adapter.itemBuilder(context, index);
          }
        },
        itemCount: adapter.itemCount + 1,
        controller: _scrollController,
      ));
    }

    if (state.isLoading) {
      widgets.add(Center(
          child: SizedBox(
              width: 110,
              height: 110,
              child: Card(
                  key: null,
                  color: Colors.black45,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(15.0),
                  ),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    mainAxisSize: MainAxisSize.min,
                    children: <Widget>[
                      SpinKitFadingCircle(
                        color: Colors.blue,
                        size: 50,
                      ),
                      Padding(
                        padding: const EdgeInsets.only(
                          top: 20.0,
                        ),
                        child: new Text(
                          "正在加载...",
                          style: TextStyle(fontSize: 12.0, color: Colors.white),
                        ),
                      ),
                    ],
                  )))));
    }

    return widgets;
  }

  return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        elevation: 2.0,
        backgroundColor: Colors.white,
        title: DropdownButton(
          hint: Text('全部班级'),
          underline: Text(''),
          value: state.currentClassId,
          items: classList(),
          onChanged: (item) {
            dispatch(HomeworkListActionCreator.onSelectClass(item));
          },
        ),
      ),
      body: Container(
        child: RefreshIndicator(
          child: Stack(
            children: _listView(),
          ),
          onRefresh: () {
            final Completer<void> completer = Completer<void>();
            dispatch(
                HomeworkListActionCreator.onReload(() => completer.complete()));
            return completer.future;
          },
        ),
      ));
}
